package com.zzy.database.service.Impl;

import com.zzy.database.mapper.AccountMapper;
import com.zzy.database.pojo.Account;
import com.zzy.database.service.AccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Override
    public void openAccount(Account account) {
        log.info("Received account: {}", account.toString());
        log.info("Customer ID: {}", account.getCustomer_id());

        int exists = accountMapper.checkCustomerExists(account.getCustomer_id());
        log.info("Customer exists result: {}", exists);
        if (accountMapper.checkCustomerExists(account.getCustomer_id()) == 0) {
            throw new RuntimeException("客户不存在");
        }
        if (accountMapper.checkBranchExists(account.getBranch_id()) == 0) {
            throw new RuntimeException("支行不存在");
        }
        accountMapper.openAccount(account);
    }

    @Override
    public void deleteAccount(String accountId) {
        accountMapper.deleteAccount(accountId);
    }

    @Override
    public Account getAccountInfo(String accountId) {
        return accountMapper.getAccountInfo(accountId);
    }

    @Override
    public List<Account> getAllAccounts() {
        return accountMapper.getAllAccounts();
    }

    @Override
    public List<Account> getAccountsByCustomerId(String customerId) {
        return accountMapper.getAccountsByCustomerId(customerId);
    }

    @Override
    public List<Account> getAccountsByBranchId(String branchId) {
        return accountMapper.getAccountsByBranchId(branchId);
    }

    @Override
    @Transactional
    public void updateBalance(String accountId, double amount) throws Exception {
        Account account = accountMapper.getAccountInfo(accountId);
        if (account == null) {
            throw new Exception("账户不存在");
        }

        double newBalance = account.getBalance() + amount;
        if (newBalance < 0) {
            throw new Exception("余额不足，当前余额: " + account.getBalance() + ", 尝试操作金额: " + amount);
        }

        accountMapper.updateAccountBalance(accountId, amount);
    }

    @Override
    public double getTotalBalanceByBranch(String branchId) {
        return accountMapper.getTotalBalanceByBranch(branchId);
    }
}